package milk.net
{
	import flash.display.Loader;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	public class BaseLoader extends EventDispatcher implements ILoadItem
	{	
		protected var data:*;
		protected var loader:*;
		
		public function BaseLoader()
		{
			super(this);
		}
		
		public function load(request:URLRequest):void{
			
		}
		
		protected function bindLoader(loader:IEventDispatcher,isBool:Boolean):void{
			
			if(isBool){
				loader.addEventListener(Event.COMPLETE,successHandler);
				loader.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
				loader.addEventListener(IOErrorEvent.NETWORK_ERROR,errorHandler);
				loader.addEventListener(ProgressEvent.PROGRESS,dispatch);
			}else{
				loader.removeEventListener(Event.COMPLETE,successHandler);
				loader.removeEventListener(IOErrorEvent.IO_ERROR,errorHandler);
				loader.removeEventListener(IOErrorEvent.NETWORK_ERROR,errorHandler);
				loader.removeEventListener(ProgressEvent.PROGRESS,dispatch);
			}
			
		}
		
		protected function errorHandler(event:IOErrorEvent):void{
			var target:IEventDispatcher=event.currentTarget;
			bindLoader(target,false);
			dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR,false,false,event.text,event.errorID));
		}
		
		protected function successHandler(event:Event):void{
			var target:IEventDispatcher=event.currentTarget;
			
			if(target["data"]){
				data=target["data"];
			}
			
			bindLoader(target,false);
			dispatch(event);
		}
		
		protected function dispatch(event:Event):void{
			if(hasEventListener(event.type)){
				this.dispatchEvent(event);
			}
		}
		
		
		
		public function get data():*{
			
		}
		
		
		
		
	}
}